package week01.necessary;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

public class CustomClassLoaderTest {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        MyClassLoader classLoader = new MyClassLoader();
        Object hello = classLoader.findClass("Hello").newInstance();
        hello.getClass().getMethod("hello").invoke(hello);
    }


    /**
     * 自定义classloader
     *
     * @author connor
     */
    static class MyClassLoader extends ClassLoader {
        @Override
        protected Class<?> findClass(String name) {
            try {
                String path = name.replace('.', '/').concat(".xlass");
                byte[] bytes = Files.readAllBytes(Paths.get(Objects.requireNonNull(this.getResource(path)).toURI()));
                for (int i = 0; i < bytes.length; i++) {
                    bytes[i] = (byte) (255 - bytes[i]);
                }
                return defineClass(name, bytes, 0, bytes.length);
            } catch (IOException | URISyntaxException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}
